package com.boyuan.huijiaoyu;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.easemob.chat.EMChatManager;
import com.example.contactfragment.ContactService;
import com.magicsoft.app.entity.RememberEntity;
import com.magicsoft.app.helper.AnimCommon;
import com.magicsoft.app.helper.NetworkUtil;
import com.magicsoft.app.helper.ScreenManager;
import com.magicsoft.app.helper.SharePreferenceHelper;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.helper.UpdateVersionHelper;
import com.magicsoft.app.helper.VersionHelper;
import com.magicsoft.app.wcf.listener.GetTwoRecordListener;
import com.magicsoft.app.wcf.listener.PostRecordResponseListener;
import com.magicsoft.weitown.fragment.HomeAppFragment;
import com.magicsoft.weitown.fragment.HomeContactFragment;
import com.magicsoft.weitown.fragment.HomeFoundFragment;
import com.magicsoft.weitown.fragment.HomeNewFragment;
import com.magicsoft.weitown.fragment.HomePersonalFragment;
import com.magicsoft.weitown.ui.CustomAlertDialog;
import com.magicsoft.weitown.ui.CustomDialog;

public class MainActivity extends BaseFragmentActivity implements
		OnClickListener {
	private static final String TAG = "MainActivity";
	// 弹出登录界面
	private final static int INTENT_ACTION_OPEN_LOGIN = 1;
	// 开启扫描界面
	private final static int INTENT_ACTION_OPENCAMERA = 2;
	private ContactService contactService;

	// 首页
	private RelativeLayout home_linearlayout_01;
	private ImageView home_iv_01;
	private TextView home_tv_01;
	// 通讯录
	private RelativeLayout home_linearlayout_02;
	private ImageView home_iv_02;
	private TextView home_tv_02;
	// 发现
	private RelativeLayout home_linearlayout_03;
	private ImageView home_iv_03;
	private TextView home_tv_03;
	// 应用
	private RelativeLayout home_linearlayout_04;
	private ImageView home_iv_04;
	private TextView home_tv_04;
	// 我
	private RelativeLayout home_linearlayout_05;
	private ImageView home_iv_05;
	private TextView home_tv_05;
	// FragmentManager
	private FragmentManager fragmentManager;
	// FragmentTransaction
	private FragmentTransaction fragmentTransaction;
	// 首页
	private HomeNewFragment homeFragment;
	// 通讯录
	private HomeContactFragment contactFragment;
	// 发现
	private HomeFoundFragment foundFragment;
	// 应用
	private HomeAppFragment appFragment;
	// 个人中心
	private HomePersonalFragment personalFragment;
	// app内通知
	private LocalBroadcastManager mLocalBroadcastManager;
	private BroadcastReceiver mReceiver;

	private boolean progressShow;

	// 检查更新
	private UpdateVersionHelper updateVersionHelper;
	private CustomAlertDialog SystemUpgradeDialog;
	private String accountId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		SharedPreferences sp = getSharedPreferences("a.xml", 0);
		accountId = sp.getString("id", "");
		//
		ScreenManager.getScreenManager().pushActivity(this);
		// 设置全局变量
		if (ColorHolderApplication.getInstance().mainActivity == null) {
			ColorHolderApplication.getInstance().mainActivity = this;
		}
		prepareView();

		// 两次回退键退出后 再次进入应用重新加载数据
		if (SharePreferenceHelper.IsLogin(getApplicationContext()) == true) {

			RememberEntity rememberEntity = SharePreferenceHelper
					.GetRememberEntity(getApplicationContext());
			String username = rememberEntity.getAdmin();
			String password = rememberEntity.getPsw();

			// new LoginTask().execute(username, password);

		}

		loadBaseNeedLoginMethod(true);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		if (homeFragment != null && homeFragment.isJumpOutOfAppSharing()) {
			homeFragment.setJumpOutOfAppSharing(false);
			isBackIntoTheFrontDesk = false;
		}
		super.onResume();
		// backendBecomeActive();
	}

	/**
	 * APP从后台进入前台，进行账号验证和同步数据
	 */
	// public void backendBecomeActive() {
	// // 开启登录界面
	// if (SharePreferenceHelper.IsLogin(getApplicationContext()) == false) {
	//
	// popupLogin();
	//
	// isBackIntoTheFrontDesk = false;
	//
	// } else {
	// // APP后台进入前台
	// if (isBackIntoTheFrontDesk == true) {
	//
	// isBackIntoTheFrontDesk = false;
	//
	// RememberEntity rememberEntity = SharePreferenceHelper
	// .GetRememberEntity(getApplicationContext());
	// String username = rememberEntity.getAdmin();
	// String password = rememberEntity.getPsw();
	//
	// new LoginTask().execute(username, password);
	// }
	// }
	// }

	// class LoginTask extends AsyncTask<String, Integer, String> {
	//
	// @Override
	// protected String doInBackground(String... params) {
	// // TODO Auto-generated method stub
	//
	// String username = params[0];
	// String password = params[1];
	//
	// try {
	//
	// String cookie = SharePreferenceHelper.getStringValue(
	// MainActivity.this, "COOKIE");
	//
	// if (StringUtils.isNotEmpty(cookie) && Main.c.check(cookie)) {
	// Log.i(TAG, "Main.c.check");
	// } else {
	// // 重新登陆
	// User userinfo = Main.c.login(username, password);
	// Main.c.check(Main.c.getTgc());
	// System.out.println("用户信息：" + userinfo);
	// System.out.println("tgc：" + Main.c.getTgc());
	//
	// SharePreferenceHelper.saveAccount(getApplicationContext(),
	// userinfo);
	// SharePreferenceHelper.setStringValue(MainActivity.this,
	// "COOKIE", Main.c.getTgc());
	// }
	// return "OK";
	// } catch (Exception e) {
	// // TODO Auto-generated catch block
	// System.out.println(e.getMessage());
	//
	// return getString(R.string.network_connections_wrong);
	// }
	//
	// }
	//
	// @Override
	// protected void onPostExecute(String result) {
	// // TODO Auto-generated method stub
	// super.onPostExecute(result);
	// if ("OK".equals(result)) {
	//
	// if (isBackIntoTheFrontDesk) {
	// // 检查网络是否连接
	// if (showNoNetWorkDialog(MainActivity.this)) {
	//
	// // 检测设备是否重复登录
	// /** 获取基本数据 **/
	// loadBaseNeedLoginMethod(true);
	// } else {
	// loadBaseNeedLoginMethod(false);
	// }
	// } else {
	// // 检查网络是否连接
	// if (showNoNetWorkDialog(MainActivity.this)) {
	// // 检测设备是否重复登录
	// /** 获取基本数据 **/
	// loadBaseNeedLoginMethod(true);
	// } else {
	// loadBaseNeedLoginMethod(false);
	// }
	// }
	//
	// } else {
	// ToastHelper.showMsg(MainActivity.this, result, false);
	// popupLogin();
	// }
	// }
	// }

	/**
	 * 加载所有需要登陆才运行的方法
	 * 
	 * @see onCreate初始化,backendBecomeActive后台进入前台,onActivityResult登陆成功
	 *      三个方法同时调用这个方法 !!!重要,以后所有需要初始化/数据同步的方法都应该写在这里
	 * 
	 * @param netFlag
	 *            网络是否连接 true网络连接正常 false网络无连接
	 */
	private void loadBaseNeedLoginMethod(boolean netFlag) {

		if (netFlag) {
			// 版本升级
			checkNewVersion();
//			getStatus();
		}
		// 首页数据更新
		if (homeFragment != null) {
			homeFragment.prepareData(netFlag);
			appFragment.prepareData(netFlag);
		}

		if (contactFragment != null) {
			contactFragment.prepareData();
		}

		if (appFragment != null) {
			appFragment.prepareData(netFlag);
		}

		// 个人页面数据更新
		if (personalFragment != null) {
			personalFragment.prepareData();

		}

	}

	/**
	 * 弹出登录界面
	 */
	public void popupLogin() {

		removeCookie(getApplicationContext());

		Activity activity = ScreenManager.getScreenManager().currentActivity();

		if (SharePreferenceHelper.IsLogin(getApplicationContext()) == false
				&& (AccountLoginActivity.class)
						.equals(activity != null ? activity.getClass() : null) == false) {

			Intent intent = new Intent();
			intent.setClass(MainActivity.this, AccountLoginActivity.class);
			startActivityForResult(intent, INTENT_ACTION_OPEN_LOGIN);

		}

	}

	/**
	 * 移除cookie
	 * 
	 * @param context
	 */
	private void removeCookie(Context context) {
		CookieSyncManager.createInstance(context);
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.removeAllCookie();
		CookieSyncManager.getInstance().sync();
	}

	private void prepareView() {
		// 首页
		home_linearlayout_01 = (RelativeLayout) findViewById(R.id.lay_shouye);
		home_linearlayout_01.setOnClickListener(this);
		home_iv_01 = (ImageView) findViewById(R.id.iv_01);
		home_tv_01 = (TextView) findViewById(R.id.tv_01);
		tv_unreadnum = (TextView) findViewById(R.id.tv_home_unreadnum);
		// 通讯录
		home_linearlayout_02 = (RelativeLayout) findViewById(R.id.lay_tongxunlu);
		home_linearlayout_02.setOnClickListener(this);
		home_iv_02 = (ImageView) findViewById(R.id.iv_02);
		home_tv_02 = (TextView) findViewById(R.id.tv_02);

		// 发现
		home_linearlayout_03 = (RelativeLayout) findViewById(R.id.lay_faxian);
		home_linearlayout_03.setOnClickListener(this);
		home_iv_03 = (ImageView) findViewById(R.id.iv_03);
		home_tv_03 = (TextView) findViewById(R.id.tv_03);
		// 运用
		home_linearlayout_04 = (RelativeLayout) findViewById(R.id.lay_yunyong);
		home_linearlayout_04.setOnClickListener(this);
		home_iv_04 = (ImageView) findViewById(R.id.iv_04);
		home_tv_04 = (TextView) findViewById(R.id.tv_04);
		// 我
		home_linearlayout_05 = (RelativeLayout) findViewById(R.id.lay_wo);
		home_linearlayout_05.setOnClickListener(this);
		home_iv_05 = (ImageView) findViewById(R.id.iv_05);
		home_tv_05 = (TextView) findViewById(R.id.tv_05);

		fragmentManager = getSupportFragmentManager();

		homeFragment = (HomeNewFragment) fragmentManager
				.findFragmentById(R.id.home_fragment);
		contactFragment = (HomeContactFragment) fragmentManager
				.findFragmentById(R.id.contact_fragment);
		foundFragment = (HomeFoundFragment) fragmentManager
				.findFragmentById(R.id.found_fragment);
		appFragment = (HomeAppFragment) fragmentManager
				.findFragmentById(R.id.app_fragment);
		personalFragment = (HomePersonalFragment) fragmentManager
				.findFragmentById(R.id.my_fragment);
		showHomeFragment();
		
	}

	/**
	 * 显示首页TAB
	 */
	private void showHomeFragment() {
		fragmentTransaction = fragmentManager.beginTransaction()
				.hide(homeFragment).hide(contactFragment).hide(foundFragment)
				.hide(appFragment).hide(personalFragment);
		fragmentTransaction.show(homeFragment).commitAllowingStateLoss();
		setSelectedTab(0);
	}

	@Override
	public void onClick(View v) {

		if (doubleBackToExitPressedOnce) {
			this.doubleBackToExitPressedOnce = false;
		}

		fragmentTransaction = fragmentManager.beginTransaction()
				.hide(homeFragment).hide(foundFragment).hide(contactFragment)
				.hide(appFragment).hide(personalFragment);

		switch (v.getId()) {

		case R.id.lay_shouye:
			// 首页
			fragmentTransaction.show(homeFragment).commit();
			setSelectedTab(0);
			break;
		case R.id.lay_tongxunlu:
			// 通讯录
			fragmentTransaction.show(contactFragment).commit();
			setSelectedTab(1);
			break;

		case R.id.lay_faxian:
			// 发现
			fragmentTransaction.show(foundFragment).commit();
			setSelectedTab(2);
			break;
		case R.id.lay_yunyong:
			// 应用
			fragmentTransaction.show(appFragment).commit();
			setSelectedTab(3);
			break;

		case R.id.lay_wo:
			// 个人中心
			fragmentTransaction.show(personalFragment).commit();
			setSelectedTab(4);
			break;

		default:
			break;
		}
	}

	/**
	 * 选择Tab
	 * 
	 * @param tab
	 */
	private void setSelectedTab(int tab) {

		switch (tab) {
		// 首页选中
		case 0:
			home_iv_01.setSelected(true);
			home_tv_01.setSelected(true);
			home_iv_02.setSelected(false);
			home_tv_02.setSelected(false);
			home_iv_03.setSelected(false);
			home_tv_03.setSelected(false);
			home_iv_04.setSelected(false);
			home_tv_04.setSelected(false);
			home_iv_05.setSelected(false);
			home_tv_05.setSelected(false);
			break;
		case 1:
			// 信息中心选中
			home_iv_01.setSelected(false);
			home_tv_01.setSelected(false);
			home_iv_02.setSelected(true);
			home_tv_02.setSelected(true);
			home_iv_03.setSelected(false);
			home_tv_03.setSelected(false);
			home_iv_04.setSelected(false);
			home_tv_04.setSelected(false);
			home_iv_05.setSelected(false);
			home_tv_05.setSelected(false);
			break;
		case 2:
			// 扫描选中
			home_iv_01.setSelected(false);
			home_tv_01.setSelected(false);
			home_iv_02.setSelected(false);
			home_tv_02.setSelected(false);
			home_iv_03.setSelected(true);
			home_tv_03.setSelected(true);
			home_iv_04.setSelected(false);
			home_tv_04.setSelected(false);
			home_iv_05.setSelected(false);
			home_tv_05.setSelected(false);
			break;
		case 3:
			// 设置页面选中
			home_iv_01.setSelected(false);
			home_tv_01.setSelected(false);
			home_iv_02.setSelected(false);
			home_tv_02.setSelected(false);
			home_iv_03.setSelected(false);
			home_tv_03.setSelected(false);
			home_iv_04.setSelected(true);
			home_tv_04.setSelected(true);
			home_iv_05.setSelected(false);
			home_tv_05.setSelected(false);
			break;
		case 4:
			// 我的页面选中
			home_iv_01.setSelected(false);
			home_tv_01.setSelected(false);
			home_iv_02.setSelected(false);
			home_tv_02.setSelected(false);
			home_iv_03.setSelected(false);
			home_tv_03.setSelected(false);
			home_iv_04.setSelected(false);
			home_tv_04.setSelected(false);
			home_iv_05.setSelected(true);
			home_tv_05.setSelected(true);
			break;

		default:
			break;
		}
	}

	/**
	 * 检查网络连接
	 * 
	 * @param context
	 */
	private boolean showNoNetWorkDialog(Context context) {

		int netCode = NetworkUtil.isNetworkEnabled(context);

		if (netCode == -1) {

			final CustomDialog dialog = new CustomDialog(MainActivity.this,
					R.style.qr_dialog);
			dialog.show();
			// 标题
			TextView tv_title = (TextView) dialog
					.findViewById(R.id.dialog_title);
			tv_title.setText(context.getResources().getString(
					R.string.attention));
			// 内容
			TextView tv_content = (TextView) dialog
					.findViewById(R.id.dialog_content);
			tv_content.setText(context.getResources().getString(
					R.string.network_connections_wrong));
			// 右上角取消
			ImageView imag_cancel = (ImageView) dialog
					.findViewById(R.id.dialog_img_cancel);
			imag_cancel.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.cancel();
				}
			});
			// 确定按钮
			Button btn_ok = (Button) dialog.findViewById(R.id.dialog_button_ok);
			btn_ok.setVisibility(View.GONE);
			btn_ok.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {

					dialog.cancel();
				}
			});
			// 取消按钮
			Button btn_cancel = (Button) dialog
					.findViewById(R.id.dialog_button_cancel);
			btn_cancel
					.setText(context.getResources().getString(R.string.roger));

			btn_cancel.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.cancel();
				}
			});

		} else {
			return true;
		}

		return false;
	}

	/**
	 * 弹出系统升级框不可取消
	 * 
	 * @param context
	 * @param title
	 * @param content
	 */
	public void showSystemUpgrade(String avaliable, String content) {

		if (SystemUpgradeDialog != null) {
			if ("0".equals(avaliable)) {
				SystemUpgradeDialog.show();
			} else {
				SystemUpgradeDialog.dismiss();
			}
		} else {
			if ("0".equals(avaliable)) {

				SystemUpgradeDialog = new CustomAlertDialog(MainActivity.this,
						R.style.qr_dialog);
				SystemUpgradeDialog.setCancelable(false);
				SystemUpgradeDialog.show();
				// 标题
				TextView tv_title = (TextView) SystemUpgradeDialog
						.findViewById(R.id.dialog_title);
				tv_title.setText("提示");
				// 内容
				TextView tv_content = (TextView) SystemUpgradeDialog
						.findViewById(R.id.dialog_content);
				tv_content.setText(content);
				// 确定按钮
				Button btn_ok = (Button) SystemUpgradeDialog
						.findViewById(R.id.dialog_button_ok);
				btn_ok.setVisibility(View.GONE);
			}
		}

	}

	private void getStatus() {
		if (updateVersionHelper == null) {
			updateVersionHelper = new UpdateVersionHelper(MainActivity.this);
		}

		updateVersionHelper
				.getStatus(new GetTwoRecordListener<String, String>() {

					@Override
					public void onFinish(String avaliable, String message) {
						// TODO Auto-generated method stub

						showSystemUpgrade(avaliable, message);

					}

					@Override
					public void onFailed(String Message) {
						// TODO Auto-generated method stub
						showSystemUpgrade("0", "系统升级中");
					}
				});
	}

	/**
	 * 自动升级检查
	 */
	public void checkNewVersion() {
		SharedPreferences sp = getSharedPreferences("user.xml", 0);
		boolean islogin = sp.getBoolean("islogin", false);
		if (!islogin) {
			return;
		}

		// 设置版本

		SharePreferenceHelper.setStringValue(getApplicationContext(),
				SharePreferenceHelper.LOCALVERSIONNUM,
				VersionHelper.getVersionCode(getApplicationContext()) + "");
		SharePreferenceHelper.setStringValue(getApplicationContext(),
				SharePreferenceHelper.SERVERVERSIONNUM,
				VersionHelper.getVersionCode(getApplicationContext()) + "");
		if (updateVersionHelper == null) {
			updateVersionHelper = new UpdateVersionHelper(MainActivity.this);
		}

		if (updateVersionHelper.isShowing == false) {
			updateVersionHelper.checkUpdate(new PostRecordResponseListener() {

				@Override
				public void onFinish(String succString) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onFailed(String failString) {
					// TODO Auto-generated method stub

				}
			});
		}
	}

	@Override
	protected void onPause() {
		super.onPause();

		if (AnimCommon.in != 1 && AnimCommon.out != 1) {
			super.overridePendingTransition(AnimCommon.in, AnimCommon.out);
			AnimCommon.clear();
		}

	}

	@Override
	protected void onDestroy() {
		Log.i(TAG, "MainActivity onDestroy");
		super.onDestroy();

		if (mLocalBroadcastManager != null && mReceiver != null) {

			mLocalBroadcastManager.unregisterReceiver(mReceiver);
		}
		
		EMChatManager.getInstance().logout();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		// 处理登录
		if (requestCode == INTENT_ACTION_OPEN_LOGIN) {
			if (resultCode == RESULT_OK) {
				// 登陆成功
				Log.e(TAG, "login completed");
				showHomeFragment();
				// 切换账号 重新登录 清空所有气泡（以防登陆成功后，联网获取推送信息数量失败后，上一账户的气泡仍然存在）
				/** 获取基本数据 **/
				loadBaseNeedLoginMethod(true);
				// 登陆成功后，重新绑定设备
			} else if (resultCode == RESULT_CANCELED) {
				// (两次回退键退出应用)
				Log.e(TAG, "exit by login");
				finish();

			}
		} else if (requestCode == INTENT_ACTION_OPENCAMERA) {

			if (resultCode == RESULT_OK) {

			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	// 两次返回后退出应用
	private boolean doubleBackToExitPressedOnce = false;

	@Override
	public void backClicked() {

		if (foundFragment.isShowingLoading()) {
			// 设置全部已读
			foundFragment.hideLoading();

		} else if (personalFragment.isShowingLoading()) {
			// 检测新版本
			personalFragment.hideLoading();

		} else if (contactFragment.isShowingLoading()) {

			contactFragment.hideLoading();

		} else {

			if (!doubleBackToExitPressedOnce) {
				this.doubleBackToExitPressedOnce = true;
				Message msg = mHandler.obtainMessage();
				msg.what = 3;
				mHandler.sendEmptyMessageDelayed(0, 2000);
				ToastHelper.showMsg(MainActivity.this,
						getString(R.string.exit_press_back_twice_message),
						false);
			} else {
				isBackAllowed = true;
				return;
			}

		}

	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				// 登陆成功
				if (isBackIntoTheFrontDesk) {
					// 检查网络是否连接
					if (showNoNetWorkDialog(MainActivity.this)) {

						// 检测设备是否重复登录
						/** 获取基本数据 **/
						loadBaseNeedLoginMethod(true);
					} else {
						loadBaseNeedLoginMethod(false);
					}
				} else {
					// 检查网络是否连接
					if (showNoNetWorkDialog(MainActivity.this)) {
						// 检测设备是否重复登录
						/** 获取基本数据 **/
						loadBaseNeedLoginMethod(true);
					} else {
						loadBaseNeedLoginMethod(false);
					}
				}
				break;
			case 2:
				// 登录失败
				ToastHelper.showMsg(MainActivity.this,
						getString(R.string.network_connections_wrong), false);
				popupLogin();
				break;
			case 3:
				// 双击back键退出
				doubleBackToExitPressedOnce = false;
				break;
			default:
				break;
			}
		}
	};

	private TextView tv_unreadnum;
	public void UpdataUnreadNum(int UnreadNum) {
		if (tv_unreadnum != null) {
			if (UnreadNum <= 0) {
				tv_unreadnum.setVisibility(View.GONE);
			} else {
				tv_unreadnum.setVisibility(View.VISIBLE);
				tv_unreadnum.setText(UnreadNum + "");
			}
		}
	}
	
	public void closeActivity(){
		finish();
	}
}
